import {Image, View,Canvas} from "@tarojs/components";
import {useEffect, useState} from "react";
import Taro from "@tarojs/taro";

export default ({seatData=[],initData={},selectSeat=[],seatPadding=2}) => {

  const [inited,setInited] = useState(false)
  const [seatParts,setSeatParts] = useState([])

  /**
   * 将画布转图片
   * @param part
   * @returns 图片
   */
  const drawPart=(part)=>{
    if(process.env.TARO_ENV == 'weapp'){
      let canvas = Taro.createOffscreenCanvas({type:'2d',width:part.width,height:part.height})
      const context=canvas.getContext('2d')
      for(let j=0;j<part.rows;j++){
        for(let i=0;i<part.cols;i++){
          const seat=seatData[j+part.y][i+part.x]
          drawSeat(context,seat,j,i)
        }
      }
      return context.canvas.toDataURL()
    }
    let canvas = {}
    if(process.env.TARO_ENV == 'tt') canvas = tt.createSelectorQuery()
    if(process.env.TARO_ENV == 'h5') canvas = Taro.createSelectorQuery()
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        canvas?.select("#myCanvas").node().exec((res) => {
            const canvas = res[0].node;
            const context = canvas.getContext('2d');
            canvas.width = part.width;
            canvas.height = part.height;
            for (let j = 0; j < part.rows; j++) {
                for (let i = 0; i < part.cols; i++) {
                    const seat = seatData[j + part.y][i + part.x];
                    drawSeat(context, seat, j, i);
                }
            }
            resolve(context.canvas.toDataURL());
        });
      }, 500);
    });
  }

  /**
   * 画座位
   * @param context
   * @param seat
   * @param j
   * @param i
   * @returns {Promise<void>}
   */
  const drawSeat=async(context,seat,j,i)=>{
    if (seat){
      let imgUrl = initData.imgResource[seat.label]
      if(initData?.cateArr && seat.label == "unselected"){
        imgUrl = initData.cateArr[seat.ext?.area]
      }
      context.drawImage(imgUrl,i*initData.seatSize.w+seatPadding,j*initData.seatSize.h+seatPadding,initData.seatSize.w-2*seatPadding,initData.seatSize.h-2*seatPadding)
    }
  }
  const processData = async () => {
    const rows = initData.seatMap;
    const processedRows = await Promise.all(rows.map(async row => {
      const parts = await Promise.all(row.parts.map(async part => {
        const data = {
          src: await drawPart(part),
          style: part.style
        };
        return data;
      }));
      return {
        parts,
        style: row.style
      };
    }));
    return processedRows;
  };

  useEffect(() => {
    Taro.showLoading({title:'加载中...'})
    if(seatData.length&&initData.seatMap&&!inited){
      processData().then(value => setSeatParts(value));
      setInited(true)
      Taro.hideLoading()
    }
  }, [initData,seatData]);


  return (
    <>
    {process.env.TARO_ENV != 'weapp'?<Canvas className="canvas-node" id="myCanvas" type="2d"></Canvas>:null}
    <View className='canvas-seats'>
      {
        selectSeat&&selectSeat.map((item,idx)=>{
          return (
            <Image key={item.label+idx} class='seat-item' src={initData.resource[item.label]} style={`left:${item.pos.col*initData.seatSize.w+seatPadding}px;top:${item.pos.row*initData.seatSize.h+seatPadding}px;width:${initData.seatSize.w-2*seatPadding}px;height:${initData.seatSize.h-2*seatPadding}px;`}></Image>
          )
        })
      }
      {
        seatParts.map((row,idx)=>{
          return (
            <View className='map-row' style={row.style} key={idx}>
              {
                row.parts.map(item=>{
                  return (
                    <Image src={item.src} key={item.src} style={item.style}></Image>
                  )
                })
              }
            </View>
          )
        })
      }
    </View>
    </>
  )
}
